from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models.order import Order, OrderItem
from app.models.user import User
from datetime import datetime

order_bp = Blueprint("order", __name__)


@order_bp.route("", methods=["GET"])
@jwt_required()
def get_user_orders():
    """获取当前用户的所有订单"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    # 查询参数
    page = request.args.get("page", 1, type=int)
    per_page = request.args.get("limit", 10, type=int)
    status = request.args.get("status", None, type=str)

    # 构建查询
    query = Order.query.filter_by(user_id=user_id)

    # 按状态过滤（如果提供）
    if status:
        query = query.filter_by(status=status)

    # 按创建时间降序排序
    query = query.order_by(Order.created_at.desc())

    # 分页
    pagination = query.paginate(page=page, per_page=per_page)
    orders = pagination.items

    return jsonify(
        {
            "code": 200,
            "message": "获取成功",
            "data": {
                "items": [order.to_dict() for order in orders],
                "total": pagination.total,
                "page": page,
                "pages": pagination.pages,
                "per_page": per_page,
            },
        }
    )


@order_bp.route("/detail/<string:order_number>", methods=["GET"])
@jwt_required()
def get_order_detail(order_number):
    """获取订单详情"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    # 查找订单
    order = Order.query.filter_by(order_number=order_number).first_or_404()

    # 检查是否是当前用户的订单
    if order.user_id != user_id and not user.is_staff():
        return jsonify({"error": "没有权限查看此订单"}), 403

    # 返回详细订单信息
    return jsonify({"code": 200, "message": "获取成功", "data": order.to_dict()})


@order_bp.route("/update-status/<string:order_number>", methods=["PUT"])
@jwt_required()
def update_order_status(order_number):
    """更新订单状态"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    # 获取请求数据
    data = request.get_json()
    new_status = data.get("status")

    if not new_status:
        return jsonify({"error": "缺少状态参数"}), 400

    # 验证状态值是否有效
    valid_statuses = ["pending", "processing", "completed", "cancelled"]
    if new_status not in valid_statuses:
        return jsonify({"error": "无效的状态值"}), 400

    # 查找订单
    order = Order.query.filter_by(order_number=order_number).first_or_404()

    # 检查是否是当前用户的订单
    if order.user_id != user_id:
        return jsonify({"error": "没有权限更新此订单"}), 403

    # 更新状态
    order.status = new_status
    order.updated_at = datetime.now()

    # 保存到数据库
    from main import db

    db.session.commit()

    return jsonify({"code": 200, "message": "状态更新成功", "data": order.to_dict()})


@order_bp.route("/admin/list", methods=["GET"])
@jwt_required()
def admin_get_orders():
    """管理员获取所有订单"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    # 验证用户是否为管理员
    if not user.is_admin() and not user.is_staff():
        return jsonify({"error": "没有管理员权限"}), 403

    # 查询参数
    page = request.args.get("page", 1, type=int)
    per_page = request.args.get("limit", 10, type=int)
    status = request.args.get("status", None, type=str)
    order_number = request.args.get("orderNumber", None, type=str)
    user_id_param = request.args.get("userId", None, type=int)
    start_date = request.args.get("startDate", None, type=str)
    end_date = request.args.get("endDate", None, type=str)

    # 构建查询
    query = Order.query

    # 按状态过滤
    if status:
        query = query.filter_by(status=status)

    # 按订单号搜索
    if order_number:
        query = query.filter(Order.order_number.like(f"%{order_number}%"))

    # 按用户ID过滤
    if user_id_param:
        query = query.filter_by(user_id=user_id_param)

    # 按日期范围过滤
    if start_date:
        try:
            start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
            query = query.filter(Order.created_at >= start_datetime)
        except ValueError:
            pass

    if end_date:
        try:
            # 设置结束日期为当天的结束时间
            end_datetime = datetime.strptime(end_date, "%Y-%m-%d")
            end_datetime = end_datetime.replace(hour=23, minute=59, second=59)
            query = query.filter(Order.created_at <= end_datetime)
        except ValueError:
            pass

    # 按创建时间降序排序
    query = query.order_by(Order.created_at.desc())

    # 分页
    pagination = query.paginate(page=page, per_page=per_page)
    orders = pagination.items

    return jsonify(
        {
            "code": 200,
            "message": "获取成功",
            "data": {
                "items": [order.to_dict() for order in orders],
                "total": pagination.total,
                "page": page,
                "pages": pagination.pages,
                "per_page": per_page,
            },
        }
    )


@order_bp.route("/admin/detail/<string:order_number>", methods=["GET"])
@jwt_required()
def admin_get_order_detail(order_number):
    """管理员获取订单详情"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    # 验证用户是否为管理员
    if not user.is_admin():
        return jsonify({"error": "没有管理员权限"}), 403

    # 查找订单
    order = Order.query.filter_by(order_number=order_number).first_or_404()

    # 返回详细订单信息
    return jsonify({"code": 200, "message": "获取成功", "data": order.to_dict()})


@order_bp.route("/admin/update-status/<string:order_number>", methods=["PUT"])
@jwt_required()
def admin_update_order_status(order_number):
    """管理员更新订单状态"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    # 验证用户是否为管理员
    if not user.is_admin():
        return jsonify({"error": "没有管理员权限"}), 403

    # 获取请求数据
    data = request.get_json()
    new_status = data.get("status")
    remarks = data.get("remarks")

    if not new_status:
        return jsonify({"error": "缺少状态参数"}), 400

    # 验证状态值是否有效
    valid_statuses = ["pending", "processing", "completed", "cancelled"]
    if new_status not in valid_statuses:
        return jsonify({"error": "无效的状态值"}), 400

    # 查找订单
    order = Order.query.filter_by(order_number=order_number).first_or_404()

    # 更新状态和备注
    order.status = new_status
    if remarks:
        order.remarks = remarks
    order.updated_at = datetime.now()

    # 保存到数据库
    from main import db

    db.session.commit()

    return jsonify({"code": 200, "message": "状态更新成功", "data": order.to_dict()})
